﻿using System;
using System.Security.Cryptography;
using System.Text;
using System.IO;

/// <summary>
/// 使用对称加密的例子
/// </summary>
class Class1
{

    
    public void StartDemo()
    {
        //establish symmetric algorithm
        SymmetricAlgorithm sa = Rijndael.Create();
       
        //key and iv
        sa.GenerateKey(); //产生随机的 (32*8) 位的密钥
        //sa.GenerateIV(); //初始向量，在ECB模式里面可以不用IV
        sa.Mode = CipherMode.ECB; //块处理模式
        sa.Padding = PaddingMode.Zeros; //末尾数据块的填充模式

        //establish crypto stream
        MemoryStream ms = new MemoryStream();
        CryptoStream cs = new CryptoStream(ms, sa.CreateEncryptor(), CryptoStreamMode.Write);

        //
        string plaintext; //原始文本
        byte[] cipherbytes; //加密后的数据
        byte[] finalbytes; //解密后的数据

        plaintext = "How are you? 这是一行文字。";
        byte[] plainbytes = Encoding.UTF8.GetBytes(plaintext);

        Console.WriteLine("原始文本是：\n{0}\n", plaintext);

        //加密过程
        cs.Write(plainbytes, 0, plainbytes.Length);
        cs.Close();
        cipherbytes = ms.ToArray();
        ms.Close();

        //下面的为加密过程
        ms = new MemoryStream(cipherbytes);
        cs = new CryptoStream(ms, sa.CreateDecryptor(), CryptoStreamMode.Read);
        finalbytes = new byte[plainbytes.Length];
        cs.Read(finalbytes, 0, plainbytes.Length);

        string finaltext = Encoding.UTF8.GetString(finalbytes);

        Console.WriteLine("解密后的文本是：\n{0}\n\n", finaltext);
        Console.WriteLine("按任意键继续");
        Console.ReadLine();
    }
}